#include "RunState.h"
#include "base\Input.h"
#include "utils\Log.h"
#include "base\Engine.h"
#include "game\World.h"
#include "renderer\DebugRenderer.h"
#include "utils\Profiler.h"
#include "..\..\GameEventData.h"
#include "..\..\Constants.h"

RunState::RunState(std::string name) : ds::GameState(name) {
	gEngine->addController(this);
	gEngine->addMouseController(this);
	gEngine->getEventManager().registerEventHandler(this);
}

RunState::~RunState() {
}

bool RunState::loadContent(ds::ResManager& resourceManager) {	
	m_Core = new GameCore();
	m_Core->loadContent(resourceManager);		
	return true;
}

void RunState::process(ds::EventBuffer& buffer) {
	if ( buffer.containsID(EVN_ASTEROID_DESTROYED) ) {
		gEngine->getActionManager().startAction("Blitz");
	}
	if ( buffer.containsID(EVN_GAME_OVER) ) {
		gEngine->getActionManager().startAction("GrayFade");
		m_Core->stop();
	}	
}
// ------------------------------------------------------------
//
// ------------------------------------------------------------
bool RunState::update(float elapsedTime) {	
	gEngine->getDebugRenderer()->showDrawCounter(ds::Vec2(10,10));		
	return true;
}

bool RunState::onActivation() {
	LOG(logINFO) << "RunState - activating now";
	gEngine->getWorld().deactivateLayerByName("StartScreen");
	gEngine->getWorld().activateLayerByName("HUD");
	gEngine->getWorld().activateLayerByName("Base");
	m_Core->start();
	gEngine->getWorld().debug();
	return true;
}
bool RunState::onDeactivation() {
	gEngine->getWorld().deactivateLayerByName("HUD");
	return true;
}

void RunState::OnButtonDown(int button) {
	if ( button == 1 ) {
		if ( !gEngine->getActionManager().isActive("Flash") ) {
			gEngine->getActionManager().startAction("Flash");
			m_Core->setAutofire(false);
			m_Core->setMagnetic(true);
		}		
	}
}
void RunState::OnButtonUp(int button) {
	if ( button == 1 ) {
		if ( gEngine->getActionManager().isActive("Flash") ) {
			gEngine->getActionManager().stopAction("Flash");
			m_Core->setAutofire(true);
			m_Core->setMagnetic(false);
		}
	}
}

void RunState::handlePowerup(const char* name) {
	if ( m_Core->engine()->hud().isPowerupAvailable(name)) {
		m_Core->usePowerup(name);
		m_Core->engine()->hud().usePowerup(name);
	}
}

void RunState::OnChar(char ascii,unsigned int keyState) {	
	if ( ascii == 'p') {
		gProfiler->print();
	}		
	if ( ascii == 'd') {
		gEngine->debug();
	}			
	if ( ascii == '1') {
		handlePowerup("HealthBonus");
	}	
	if ( ascii == '2') {
		handlePowerup("DoubleLaser");
	}	
	if ( ascii == '3') {
		handlePowerup("TripleLaser");
	}		
}
